<?php

global $options;
global $themename;
global $shortname;

$themename = "iGoogler";
$shortname = "iGoogler_";
$options = array (
		array("id" => "excerpt_first_p",
				"title"=>__('First paragraph as excerpt', 'igoogler'),
				"type"=>"checkbox",
				"std" => "true",
				"description" => __('If you checked this option, the first paragraph will be chosen as the excerpt.', 'igoogler')),
		array("id" => "excerpt_length",
				"title"=>__('Max length of the excerpt', 'igoogler'),
				"type"=>"text",
				"std" => "200",
				"description"=>__('This is mostly useful for many Asian users.', 'igoogler')),
		array("id" => "google-plus-one",
				"title"=>__('Google+1 Enabled', 'igoogler'),
				"type"=>"checkbox",
				"std"=>"true",
				"description"=>__("Enable Google+1 button improves the site traffic, see <a href='http://www.google.com/webmasters/+1/button/'>Google +1</a>, but may be unusable in China.", 'igoogler') ),
		array("id" => "google_custom",
				"title"=>__('Google custom search', 'igoogler'),
				"type"=>"text",
				"std"=> "",
				"description"=>__("Please Insert your Google custom search ID, ex. 009074447596699951990:e_y5ug***-#, <a href='http://www.google.com/cse/?hl=zh-CN'>Click here</a> to get one") ),
		array("id" => "single_copyright",
				"title"=>__("Copyright display", 'igoogler'),
				"type"=>"checkbox",
				"std" => "true",
				"description"=>__("If you checked this option, additional copyright words will display on each single post.", 'igoogler') ),
		array("id" => "copyright_content",
				"title"=>__("Copyright Content", 'igoogler'),
				"type"=>"textarea",
				"std" => "",
				"description"=>__("If you need custom your own copyright description, please put it here.", 'igoogler') ),
		array("id" => "google_plus_id",
				"title"=>__("Google+ profile ID", 'igoogler'),
				"type"=>"text",
				"std" => "",
				"description"=>__("This mainly helps to display Rich snippets author in google search result, goto <a href='https://plus.google.com/'>Google plus</a> to get one.", 'igoogler') ),
		array("id" => "site_stat",
				"title"=>__("Site Analytics Code", 'igoogler'),
				"type"=>"textarea",
				"std" => "",
				"description"=>__("Please input your analytics code.", 'igoogler')),
		array("id" => "h3",
				"title"=>__("Ads Display", 'igoogler'),
				"type"=>"h3",
				"std" => "",),
		array("id" => "bottom_ad",
				"title" => __("Ad on the bottom of Posts", 'igoogler'),
				"type"=>"textarea",
				"std"=>"",
				"description"=>__("Best size of 336*280 or 300*250", 'igoogler') ),
		array("id" => "respond_ad",
				"title" => __("Ad on the rightside of Comment", 'igoogler'),
				"type"=>"textarea",
				"std"=>"",
				"description"=>__("Best size of 300*250", 'igoogler') ),
);

function igoogler_option_init() {
	global $options , $loaded_option;
	foreach($options as $value) {
		$loaded_option[($value['id'])] = get_option('iGoogler_'.$value['id'], $value['std']);
	}
}

function igoogler_option($name) {
	global $loaded_option;

	if(empty($loaded_option)) igoogler_option_init();

	return $loaded_option[$name];
}


function seo_title($sep) {
	/*
	 * Print the <title> tag based on what is being viewed.
	*/
	global $page, $paged;

	wp_title( $sep, true, 'right' );

	// Add the blog name.
	bloginfo( 'name' );

	// Add the blog description for the home/front page.
	$site_description = get_bloginfo( 'description', 'display' );
	if ( $site_description && ( is_home() || is_front_page() ) )
		echo " | $site_description";

	// Add a page number if necessary:
	if ( $paged >= 2 || $page >= 2 )
		echo ' | ' . sprintf(__('Paged %s', 'igoogler'), max( $paged, $page ) );
}

function time_since($older_date, $newer_date = false)
{
	$chunks = array(
			array(60 * 60 * 24 * 7, 'week'),
			array(60 * 60 * 24 , 'day'),
			array(60 * 60 , 'hour'),
			array(60 , 'minute'),
	);
	$newer_date = ($newer_date == false) ? (time()+(60*60*get_option("gmt_offset"))) : $newer_date;
	$since = $newer_date - $older_date;
	if($since < 604800)
	{
		for ($i = 0, $j = count($chunks); $i < $j; $i++)
		{
			$seconds = $chunks[$i][0];
			$name = $chunks[$i][1];
			if (($count = floor($since / $seconds)) != 0)
			{
				break;
			}
		}
		$output = "$count {$name}";
		if($count>1)
			$output .= 's';
		return $output." ago";
	}else{
		the_time('Y-m-j');
	}
}

function get_type() {
	if(is_home()) {
		_e('Home');
	}
	elseif(is_single()) {
		_e('Post');
	}
	elseif(is_page()) {
		_e('Page');
	}
	elseif(is_category()) {
		_e('Category');
	}
	elseif(is_tag()) {
		_e('Tag');
	}
	elseif(is_date()) {
		_e('Date');
	}
	elseif(is_author()) {
		_e('Author');
	}
	elseif(is_search()) {
		_e('Search');
	}
	elseif(is_404()) {
		_e('404');
	}
}

function get_description() {
	if ( is_date() ) {
		global $wpdb, $wp_locale;
		
		$year = get_query_var('year');
		$monthnum = get_query_var('monthnum');
		$day = get_query_var('day');
		$t_sep = ' ';
		
		$title = $year;
		if ( !empty($monthnum) )
			$title .= $t_sep . $wp_locale->get_month($monthnum);
		if ( !empty($day) )
			$title .= $t_sep . zeroise($day, 2);
		
		printf(__('Archives for <em>%s</em>, ', 'igoogler'), $title);
		
		show_query_num();
	}
	elseif(is_category() || is_tag()) {
		$term = get_queried_object();
		printf(__('Archives for <em>%s</em>, ', 'igoogler'), $term->name );
		show_query_num();
	}
	elseif(is_single()) {
		global $post;
		printf(__('By %s, posted %s, under %s', 'igoogler'), '<a href="'.get_author_posts_url($post->post_author).'">'.get_the_author_meta('display_name', $post->post_author).'</a>', '<em>'.get_the_time( get_option( 'date_format' ) ).'</em>', get_the_category_list(', '));
	}
	elseif(is_page()) {
		global $post;
		echo '<a href="'.get_bloginfo("url").'" title="">'.__('Home').'</a>';
		$parent_id  = $post->post_parent;
		$breadcrumbs = array();
		while ($parent_id) {
			$page = get_page($parent_id);
			$breadcrumbs[] = '<a href="'.get_permalink($page->ID).'" title="">'.get_the_title($page->ID).'</a>';
			$parent_id  = $page->post_parent;
		}
		$breadcrumbs = array_reverse($breadcrumbs);
		foreach ($breadcrumbs as $crumb) echo ' / '.$crumb;
		echo ' / <em>'.get_the_title().'</em>';
	}
	else {
		show_query_num();
	}
}

function search_words (){
	$search_engine = array ('google.com'=>'q','baidu.com'=>'wd','bing.com'=>'q','yahoo.com'=>'p','sogou.com'=>'query','soso.com'=>'w');
	if(is_search()&&$_GET['s']!='')
		return $_GET['s'];
	else {
		foreach($search_engine as $key=>$value)
			if(strpos($_SERVER['HTTP_REFERER'],$key))
			{
				// Get the position of the keywords begin
				$pos1 = strpos($_SERVER['HTTP_REFERER'],'&'.$value.'=');
				if(!$pos1) {
					$pos1 = strpos($_SERVER['HTTP_REFERER'],'?'.$value.'=');
				}
				// Get the position of the keywords end
				$pos2 = strpos($_SERVER['HTTP_REFERER'],'&',$pos1+1);
				
				// length of value
				$len = strlen($value);
				
				// get words
				if($pos2!=0)
					$str = substr($_SERVER['HTTP_REFERER'],$pos1+$len+2,$pos2-$pos1-$len-2);
				else
					$str = substr($_SERVER['HTTP_REFERER'],$pos1+$len+2);
				$encode1 = mb_detect_encoding($str, array('ASCII','CP936','gb2312','UTF-8'));
				if($encode1 != "CP936")
				{
					$str = urldecode($str);
					$encode2 = mb_detect_encoding($str, array('ASCII','gb2312','GBK','UTF-8'));
					if($encode2 == "EUC-CN")
						$str = mb_convert_encoding($str,'utf-8','gb2312');
				}
				return $str;
			}
			return false;
	}
}

function show_query_num() {
	global $wp_query;
	$request = $wp_query->request;
	$posts_per_page = intval(get_query_var('posts_per_page'));
	$paged = intval(get_query_var('paged'));
	$numposts = $wp_query->found_posts;
	$max_page = $wp_query->max_num_pages;
	if(empty($paged) || $paged == 0) {
		$paged = 1;
	}
	if(is_404())
		$current_num = 0;
	else
		$current_num = (($paged-1)*$posts_per_page)+1;
	$str = sprintf(__('Page %s of about %s results (%s seconds) ', 'igoogler'),$max_page, $numposts, timer_stop(0));
	echo $str;
}

function igoogler_paged_navi() {
	global $wp_query, $wp_rewrite;
	if($wp_query->max_num_pages < 2)
		return;

	if(get_query_var('paged') < 2) {
		echo '<span class="page-numbers prev-none ">&nbsp;</span>';
	}
	$big = $wp_query->max_num_pages;
	$param =  array(
			'format' => '?paged=%#%',
			'current' => max( 1, get_query_var('paged') ),
		    'prev_text'    => __('&laquo; Prev', 'igoogler'),
		    'next_text'    => __('Next &raquo;', 'igoogler'),
			'total' => $wp_query->max_num_pages,
	);
	
	if( $wp_rewrite->using_permalinks() ) {
	    $param['base'] = user_trailingslashit( trailingslashit( remove_query_arg('s',get_pagenum_link(1) ) ) . 'page/%#%/', 'paged');
	}
	if( !empty($wp_query->query_vars['s']) ) {
	    $param['add_args'] = array('s'=>get_query_var('s'));
	}

	echo paginate_links($param);

	if(get_query_var('paged') == $wp_query->max_num_pages) {
		echo '<span class="page-numbers next-none ">&nbsp;</span>';
	}
}

function wp_get_related_posts_igoogler($number = 5,$limit = 5) {
	global $wpdb, $post;
	$temp_post = $post;
	
	$q = 'SELECT tt.term_id FROM '. $wpdb->term_taxonomy.'  tt, ' . $wpdb->term_relationships.' tr WHERE tt.taxonomy = \'category\' AND tt.term_taxonomy_id = tr.term_taxonomy_id AND tr.object_id = '.$post->ID;
	$cats = $wpdb->get_results($q);

	if(!$post->ID){
		return;
	}
	$now = current_time('mysql', 1);
	$tags = wp_get_post_tags($post->ID);

	$taglist = "'" . $tags[0]->term_id. "'";

	$tagcount = count($tags);
	if ($tagcount > 1) {
		for ($i = 1; $i < $tagcount; $i++) {
			$taglist = $taglist . ", '" . $tags[$i]->term_id . "'";
		}
	}

	if ($limit) {
		$limitclause = "LIMIT $limit";
	}	else {
		$limitclause = "LIMIT 5";
	}

	$q = "SELECT p.ID, p.post_title, p.post_content,p.post_excerpt, p.post_date,  p.comment_count, count(t_r.object_id) as cnt FROM $wpdb->term_taxonomy t_t, $wpdb->term_relationships t_r, $wpdb->posts p WHERE t_t.taxonomy ='post_tag' AND t_t.term_taxonomy_id = t_r.term_taxonomy_id AND t_r.object_id  = p.ID AND (t_t.term_id IN ($taglist)) AND p.ID != $post->ID AND p.post_status = 'publish' AND p.post_date_gmt < '$now' GROUP BY t_r.object_id ORDER BY cnt DESC, p.post_date_gmt DESC $limitclause;";

	$related_posts = $wpdb->get_results($q);

	$output = "";

	foreach ($related_posts as $related_post ){
		$output .= '<li>';
		$output .=  '<a href="'.get_permalink($related_post->ID).'" title="'.wptexturize($related_post->post_title).'">'.wptexturize($related_post->post_title).'</a>';
		$output .=  '</li>';
	}
	if(empty($related_posts)) $output .= '<li>No related posts.</li>';
	$post = $temp_post;
	return $output;
}

function get_most_comments_posts_igoogler ($number = 5)
{
	global $wpdb,$post;
	$query = $wpdb->get_results('SELECT `ID` , `comment_count`
			FROM  `wp_posts`
			WHERE `post_type` = "post" AND `post_status` = "publish"
			ORDER BY  `comment_count` DESC
			LIMIT 0 , '.$number,'ARRAY_A');
	$temp_post = $post;
	foreach($query as $value):
	$fpost=get_post(intval($value['ID']));
	setup_postdata($fpost);
	$output.='<li><a href="'.get_permalink($fpost->ID).'" title="'.get_the_title($fpost->ID).'">'.get_the_title($fpost->ID).'</a> - '.$value[comment_count].' '.__('Comments', 'igoogler').'</li>';
	endforeach;
	$post= $temp_post;
	return $output;
}

function get_random_posts_igoogler($number = 5)
{
	global $post;
	$temp_post = $post;
	$output = '';
	$rand_posts = get_posts('numberposts='.$number.'&orderby=rand');
	foreach( $rand_posts as $fpost ) :
	$output.='<li><a href="'.get_permalink($fpost->ID).'" title="'.get_the_title($fpost->ID).'">'.get_the_title($fpost->ID).'</a> </li>';
	endforeach;
	$post = $temp_post;
	return $output;
}

function get_latest_posts_igoogler($number = 5)
{
	global $post;
	$temp_post = $post;
	$output = '';
	$rand_posts = get_posts('numberposts='.$number.'&orderby=ID&order=DESC');
	foreach( $rand_posts as $fpost ) :
	$output.='<li><a href="'.get_permalink($fpost->ID).'" title="'.get_the_title($fpost->ID).'">'.get_the_title($fpost->ID).'</a> </li>';
	endforeach;
	$post = $temp_post;
	return $output;
}

/********************************************/
/* $Id: wp-utf8-excerpt.php 23 2010-01-01 14:23:11Z Betty $ */

/* if the host doesn't support the mb_ functions, we have to define them. From Yskin's wp-CJK-excerpt, thanks to Yskin. */
if ( !function_exists('mb_strlen') ) {
	function mb_strlen ($text, $encode) {
		if ($encode=='UTF-8') {
			return preg_match_all('%(?:
					[\x09\x0A\x0D\x20-\x7E]           # ASCII
					| [\xC2-\xDF][\x80-\xBF]            # non-overlong 2-byte
					|  \xE0[\xA0-\xBF][\x80-\xBF]       # excluding overlongs
					| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
					|  \xED[\x80-\x9F][\x80-\xBF]       # excluding surrogates
					|  \xF0[\x90-\xBF][\x80-\xBF]{2}    # planes 1-3
					| [\xF1-\xF3][\x80-\xBF]{3}         # planes 4-15
					|  \xF4[\x80-\x8F][\x80-\xBF]{2}    # plane 16
			)%xs',$text,$out);
		}else{
			return strlen($text);
		}
	}
}

/* from Internet, author unknown */
if (!function_exists('mb_substr')) {
	function mb_substr($str, $start, $len = '', $encoding="UTF-8"){
		$limit = strlen($str);

		for ($s = 0; $start > 0;--$start) {// found the real start
			if ($s >= $limit)
				break;

			if ($str[$s] <= "\x7F")
				++$s;
			else {
				++$s; // skip length

				while ($str[$s] >= "\x80" && $str[$s] <= "\xBF")
					++$s;
			}
		}

		if ($len == '')
			return substr($str, $s);
		else
			for ($e = $s; $len > 0; --$len) {//found the real end
			if ($e >= $limit)
				break;

			if ($str[$e] <= "\x7F")
				++$e;
			else {
				++$e;//skip length

				while ($str[$e] >= "\x80" && $str[$e] <= "\xBF" && $e < $limit)
					++$e;
			}
		}

		return substr($str, $s, $e - $s);
	}
}

/* the real excerpt function */
if (!function_exists('utf8_excerpt')) {
	function utf8_excerpt ($text) {
		global $post;

		if ( '' == $text ) {
			$home_excerpt_length = igoogler_option('excerpt_length');
			$archive_excerpt_length = igoogler_option('excerpt_length');
			//set default options
			if ('' == $allowd_tag) {
				$allowd_tag = '<span><strong>';
			}
			if ('' == $home_excerpt_length) {
				$home_excerpt_length = 200;
			}
			if ('' == $archive_excerpt_length) {
				$archive_excerpt_length = 150;
			}
			if ('' == $read_more_link) {
				$read_more_link = ' ...';
			}

			if (is_home()) {
				$length = $home_excerpt_length;
			} else {
				$length = $archive_excerpt_length;
			}

			//get and trim the text
			$text = $post->post_content;
			$text = apply_filters('the_content', $text);
			$text = str_replace(']]>', ']]&gt;', $text);
			$text = trim($text);

			//			check if the post is already short
			if($length > mb_strlen($text = strip_tags($text, $allowd_tag), 'utf-8')) {
				return force_balance_tags($text);
			}

			//          check if there is a <!--more--> tag
			$more_position = stripos ($text, "<!--more-->");
			if ($more_position !== false) {
				$text = substr ($text, 0, $more_position);
			}
			else {

				// strip tags now, otherwise the <!--more--> tag is also stripped
				$text = strip_tags($text, $allowd_tag);
				$text = trim($text);
					
				//		 		check if the character is worth counting (ie. not part of an HTML tag). From Bas van Doren's Advanced Excerpt, thanks to Bas van Doren.
				$num = 0;
				$in_tag = false;
				for ($i=0; $num<$length || $in_tag; $i++) {
					if(mb_substr($text, $i, 1) == '<')
						$in_tag = true;
					elseif(mb_substr($text, $i, 1) == '>')
					$in_tag = false;
					elseif(!$in_tag)
					$num++;
				}
				$text = mb_substr ($text,0,$i, 'utf-8');
			}

		}

		$text .= " ...";
		$text = force_balance_tags($text);

		return $text;
	}
}

function first_p_excerpt()
{
	global $post;
	
	if(!empty($post->post_excerpt)) {
		return $post->post_excerpt;
	}

	if(preg_match('/<p>(.*)<\/p>/iU',trim(strip_tags($post->post_content,"<p>")),$matches)){
		return $matches[1];
	} else {
		$post_content = explode("\n",trim(strip_tags($post->post_content)));
		return $post_content ['0'];
	}
}

if(igoogler_option('excerpt_first_p'))
	add_filter('get_the_excerpt', 'first_p_excerpt');
else
	add_filter('get_the_excerpt', 'utf8_excerpt');
/********************************************/

function igoogler_plusone($size = "standard", $annotation = "inline", $url = "") {
	if(!igoogler_option('google-plus-one')) {
		return;
	}
	$str = '<div class="g-plusone" data-size="'.$size.'" data-annotation="'.$annotation.'" ';
	if(!empty($url))
		$str .= 'data-href="'.$url.'"';
	$str .= '></div>';
	
	echo $str;
	
}

if ( ! function_exists( 'igoogler_comment' ) ) :

function igoogler_comment( $comment, $args, $depth ) {
	$GLOBALS['comment'] = $comment;
	switch ( $comment->comment_type ) :
		case 'pingback' :
		case 'trackback' :
	?>
	<li class="post pingback">
		<p><?php _e( 'Pingback:', 'igoogler' ); ?> <?php comment_author_link(); ?><?php edit_comment_link( __( 'Edit', 'igoogler' ), '<span class="edit-link">', '</span>' ); ?></p>
	<?php
			break;
		default :
	?>
<li class="comment" id="comment-<?php comment_ID() ?>">
	<div class="brd">
		<div class="author">
			<?php if (function_exists('get_avatar') && get_option('show_avatars')) { 
				echo get_avatar($comment, 48);
			} ?>
		</div>
		<div class="info">
			<div class="meta">
				<span class="name"> <a class="url" target="_blank" href="<?php comment_author_url() ?>">  <?php comment_author(); ?> </a></span>
				<?php comment_date('Y-m-j');?>
				&nbsp;
				<?php comment_reply_link( array_merge( $args, array( 'depth' => $depth, 'max_depth' => $args['max_depth'] ) ) ); edit_comment_link(__('Edit'), ' | ', '');?>
			</div>
			<?php if ($comment->comment_approved == '0') : ?>
			<p>
				<small><?php _e('Your comment is awaiting approval', 'igoogler');?>
				</small>
			</p>
			<?php endif; ?>
			<div id="commentbody-<?php comment_ID() ?>">
				<?php comment_text(); ?>
			</div>
		</div>
		<div class="clear">&nbsp;</div>
        <?php paginate_comments_links();?>
	</div>
	<?php
			break;
	endswitch;
}
endif; // ends check for igoogler_comment()


?>